/*
 * @Title ThreadDAOImpl.java
 * @Copyright Copyright 2010-2015 Yann Software Co,.Ltd All Rights Reserved.
 * @Description��
 * @author Yann
 * @date 2015-8-8 ����11:00:38
 * @version 1.0
 */
package com.smallkingson.ylib.net.download;

import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.smallkingson.ylib.core.Yr;
import com.smallkingson.ylib.db.YSQLites;

public class ThreadDAO {

	private SQLiteOpenHelper mHelper;

	public ThreadDAO(Context context) {
		mHelper = new SQLiteOpenHelper(context, "YDownload.db", null, 1) {

			@Override
			public void onUpgrade(SQLiteDatabase db, int oldVersion,
					int newVersion) {
			}

			@Override
			public void onCreate(SQLiteDatabase db) {
				YSQLites.createTable(db, ThreadInfo.class);
			}
		};
	}

	public synchronized void insertThread(ThreadInfo threadInfo) {
		try {
			YSQLites.insert(mHelper, threadInfo);
		} catch (Exception e) {
			Yr.logError(e);
		}
	}

	public synchronized void deleteThread(String url) {
		try {
			YSQLites.delete(mHelper, ThreadInfo.class, "url='?'", url);
		} catch (Exception e) {
			Yr.logError(e);
		}
	}

	public synchronized void updateThread(ThreadInfo mThreadInfo) {
		try {

			YSQLites.update(
					mHelper,
					mThreadInfo,
					YSQLites.setParamsToSql("url='?' and id=?",new Object[]{
							mThreadInfo.getUrl(), mThreadInfo.getId() + ""
					}),
					"finished");
		} catch (Exception e) {
			Yr.logError(e);
		}
	}

	public synchronized List<ThreadInfo> getThreads(String url) {
		try {
			return YSQLites.select(mHelper, ThreadInfo.class, "url='?'", new Object[]{url});
		} catch (Exception e) {
			Yr.logError(e);
		}
		return null;
	}

	public synchronized boolean isExists(String url, int thread_id) {
		try {
			return YSQLites.select(mHelper, ThreadInfo.class,
					"url='?' and id=?",new Object[]{ url, thread_id + ""}).size() > 0;
		} catch (Exception e) {
			Yr.logError(e);
		}
		return false;
	}
}
